﻿using KPIS.GERP.Models.ICM;
using System;
using System.Linq;
using System.Web.Mvc;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class BidderQuotationController : Controller
    {
        public ActionResult GetPrItemPrice(int Id)
        {
            using (var service = new PurchaseRequestItemService.PurchaseRequestItemServiceClient()) {
                var PrItemlst = service.Select(new Models.ICM.PurchaseRequestItem() { PrItemId = Id },null);
                var result = PrItemlst.FirstOrDefault().Price;
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            
        }

        public ActionResult GetPrItemQty(int Id)
        {
            using (var service = new PurchaseRequestItemService.PurchaseRequestItemServiceClient())
            {
                var PrItemlst = service.Select(new Models.ICM.PurchaseRequestItem() { PrItemId = Id }, null);
                var result = PrItemlst.FirstOrDefault().Qty;
                return Json(result, JsonRequestBehavior.AllowGet);
            }

        }

        public ActionResult GetPrItemAmount(int Id)
        {
            using (var service = new PurchaseRequestItemService.PurchaseRequestItemServiceClient())
            {
                var PrItemlst = service.Select(new Models.ICM.PurchaseRequestItem() { PrItemId = Id }, null);
                var result = PrItemlst.FirstOrDefault().Amount;
                return Json(result, JsonRequestBehavior.AllowGet);
            }

        }

        public ActionResult Index(int BidderId, bool IsFromOther = false)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBidderQuotation(new BidderQuotation { BidderId = BidderId }, new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense" });

            var bidderModel = service.SelectBidder(new Bidder { BidderId = BidderId }, new[] { "Bid", "PurchaseRequest" }).FirstOrDefault();
            ViewBag.BidderId = bidderModel.BidderId;
            ViewBag.IsFromOther = IsFromOther;

            if (bidderModel.BidId != null)
            {
                ViewBag.bEditable = (DateTime.Now >= bidderModel.Bid.OfferDateTimeStart && DateTime.Now <= bidderModel.Bid.OfferDateTimeEnd);
                ViewBag.BidModel = bidderModel.Bid;
            }
            else
            {
                var RecordStatus = bidderModel.PurchaseRequest.RecordStatus;
                ViewBag.bEditable = RecordStatus == Models.SYS.RecordStatus.WaitStatus || RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;
            }

            return View(model);
        }

        public ActionResult Details(int id, bool IsFromOther = false)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBidderQuotation(new BidderQuotation { BidderQuoId = id }
                , new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense", "Bidder.Bid", "Bidder.PurchaseRequest" }).FirstOrDefault();
            ViewBag.IsFromOther = IsFromOther;

            if (model.Bidder.BidId != null)
            {

                ViewBag.bEditable = (DateTime.Now >= model.Bidder.Bid.OfferDateTimeStart && DateTime.Now <= model.Bidder.Bid.OfferDateTimeEnd);
                ViewBag.BidModel = model.Bidder.Bid;
            }
            else
            {
                var RecordStatus = model.Bidder.PurchaseRequest.RecordStatus;
                ViewBag.bEditable = RecordStatus == Models.SYS.RecordStatus.WaitStatus || RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;
            }

            return View(model);
        }

        public ActionResult Create(int BidderId)
        {
            var service = new BidService.BidServiceClient();
            var model = new Models.ICM.BidderQuotation();
            model.BidderId = BidderId;
            model.Selected = "0";
            ViewBag.PrId = service.SelectBidder(new Bidder() { BidderId = BidderId }, null).FirstOrDefault().PrId;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(BidderQuotation model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new BidService.BidServiceClient();
                    var id = service.InsertBidderQuotation(model, Class.GimsMembership.CurrentEmpId);
                    var modelBidder = service.SelectBidder(new Bidder() { BidderId = model.BidderId ?? 0 }, null).FirstOrDefault();
                    modelBidder.OfferStatus = "1";
                    service.UpdateBidder(modelBidder, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = id });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBidderQuotation(new BidderQuotation { BidderQuoId = Id }, new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense" }).FirstOrDefault();

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int Id, BidderQuotation model)
        {
            try
            {
                var servicePrItem = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
                var prItemModel = servicePrItem.Select(new PurchaseRequestItem() { PrItemId = model.PrItemId.Value }
                    , new[] { "PurchaseRequest.MasPurchaseMethod", "MasResourceItem", "MasBudgetExpense" }).FirstOrDefault();

                if (ModelState.IsValid)
                {
                    var service = new BidService.BidServiceClient();

                    if (!prItemModel.PurchaseRequest.MasPurchaseMethod.IsBid ?? true)
                    {
                        if (model.NetAmount > 0)
                        {
                            model.Selected = "1";
                        }
                        else
                        {
                            model.Selected = "0";
                        }

                        var otherQuotationModels = service.SelectBidderQuotation(new BidderQuotation() { PrItemId = model.PrItemId }, null);

                        foreach (BidderQuotation otherQuotationModel in otherQuotationModels)
                        {
                            if (otherQuotationModel.BidderQuoId != model.BidderQuoId && otherQuotationModel.NetAmount > 0)
                            {
                                model.PurchaseRequestItem = prItemModel;
                                ModelState.AddModelError("", "มีรายการอื่นที่มียอดเงินอยู่แล้ว กรุณาแก้ไขยอดเงินของรายการอื่นๆ ให้เป็น 0 ก่อน");
                                return View(model);
                            }
                        }
                    }

                    service.UpdateBidderQuotation(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = model.BidderQuoId });
                }

                model.PurchaseRequestItem = prItemModel;
                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new BidService.BidServiceClient();
                var BidderId = service.SelectBidderQuotation(new BidderQuotation { BidderQuoId = id }, null).FirstOrDefault().BidderId;
                service.DeleteBidderQuotation(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index", new { BidderId = BidderId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new BidService.BidServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteBidderQuotation(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Empty", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");
                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }
    }
}
